//
//  RegistViewController.m
//  EnterpriseEdition
//
//  Created by ypj on 2021/10/8.
//

#import "RegistViewController.h"
#import "PersonInfoViewController.h"
#import "XIeYiPageVC.h"


@interface RegistViewController ()<UITextFieldDelegate>

@property (nonatomic, assign) NSInteger timeout;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) NSString *agreeString;

@end

@implementation RegistViewController

-(void)viewWillAppear:(BOOL)animated{
   [super viewWillAppear:animated];
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self layoutCustomNav:self.view title:@"注册"];
    
    [self.loginImage createBordersWithColor:nil withCornerRadius:5.0 andWidth:0];
    self.agreeString = @"1";
    self.agreeButton.selected = YES;
    [self.agreeButton setImage:Image(@"small_select_icon") forState:UIControlStateNormal];
    [self.passwordClearButton setImage:Image(@"login_noShowPassWord") forState:UIControlStateSelected];
    [self.passwordClearButton setImage:Image(@"login_showPassWord") forState:UIControlStateNormal];
    
    self.phoneTF.delegate = self;
    self.codeTF.delegate = self;
    [self.registButton createBordersWithColor:nil withCornerRadius:4.0 andWidth:0];
    [self.registButton whenTapped:^{
        [self commitRegist];
    }];
    [self.xieYiButton whenTapped:^{
        XIeYiPageVC *VC = [[XIeYiPageVC alloc] init];
        VC.titleString = @"平台服务协议";
        VC.type = @"1";
       [self.navigationController pushViewController:VC animated:YES];
    }];
    [self.yinSiButton whenTapped:^{
        XIeYiPageVC *VC = [[XIeYiPageVC alloc] init];
        VC.titleString = @"隐私协议";
        VC.type = @"2";
        [self.navigationController pushViewController:VC animated:YES];
    }];
    [self.codeButton whenTapped:^{
        [self.view endEditing:YES];
        [self getCodeData];
    }];
    [self.view whenTapped:^{
        [self.view endEditing:YES];
    }];
    [self.codeClearButton whenTapped:^{
        self.codeTF.text = @"";
    }];
    [self.passwordClearButton whenTapped:^{
        self.passwordClearButton.selected = !self.passwordClearButton.selected;
        self.passTF.secureTextEntry = self.passwordClearButton.isSelected;
    }];
}

- (IBAction)agreeButtonClick:(UIButton *)sender {
    if (self.agreeButton.selected == YES){
        [self.agreeButton setImage:Image(@"small_unSelect_icon") forState:UIControlStateNormal];
        self.agreeButton.selected = NO;
        self.agreeString = @"0";
    } else {
        [self.agreeButton setImage:Image(@"small_select_icon") forState:UIControlStateNormal];
        self.agreeButton.selected = YES;
        self.agreeString = @"1";
    }
}


-(void)getCodeData{
    if(![_phoneTF.text isValidPhone]){
        showAlert(@"手机号码不正确");
        return;
    }
    self.codeButton.enabled = NO;
    NSString *url = [NSString stringWithFormat:@"%@?phone=%@&type=1",BEFORE_SMS_URL,self.phoneTF.text];
    
    [MSNetworkManager postRevertUrl:url params:@{} success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        if (isSuccess) {
            self.timeout = kCodeTime;
            [self.codeButton setTitle:[NSString stringWithFormat:@"%d秒", kCodeTime] forState:UIControlStateNormal];
            showAlert(@"获取验证码成功");
            [self applicationEnterBackground];
            BD_WEAKSELF
            [[kNotifyCenter rac_addObserverForName:UIApplicationDidEnterBackgroundNotification object:nil] subscribeNext:^(NSNotification * _Nullable note){
                [weakSelf applicationEnterBackground];
            }];
        }
        else {
            [self msgCodeFail];
        }
        
        
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
        showAlert(@"验证码获取失败");
        [self msgCodeFail];
    } withShowHud:YES];
}

- (void)applicationEnterBackground {
    [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
    //加入定时器，用来控制后台运行时间
    if (!_timer) {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDown) userInfo:nil repeats:YES];
        //[_timer fire];
    }
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}
- (void)countDown {
    _timeout--;
    [self.codeButton setTitle:[NSString stringWithFormat:@"%ld秒",(long)_timeout] forState:UIControlStateNormal];
    if (_timeout == 0){
        [self msgCodeFail];
    }
}

- (void)msgCodeFail {
    [_timer invalidate];
    _timer = nil;
    [_codeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    _codeButton.enabled = YES;
    _timeout = kCodeTime;
}

-(void)commitRegist{
    [self.view endEditing:YES];
    if (![self.phoneTF.text isValidPhone]) {
        showAlert(@"手机号码不正确");
        return;
    }
    if (self.codeTF.text.length == 0){
        showAlert(@"验证码不能为空");
        return;
    }
    if (self.passTF.text.length == 0||self.passTF.text.length<8){
        showAlert(@"密码不能为空或长度不能小于8位");
        return;
    }
    if (self.passTF.text.length > 18) {
        showAlert(@"密码长度不能大于18位");
        return;
    }
    if ([self.passTF.text isValidPwd] == NO) {
        showAlert(@"密码必须为数字英文混合设置");
        return;
    }
    if ([self.agreeString isEqualToString:@"0"]){
        showAlert(@"请先阅读平台服务协议和隐私协议");
        return;
    }

    NSString *url = [NSString stringWithFormat:@"%@?code=%@&passWord=%@&phone=%@&username=%@",REGISTER_URL,self.codeTF.text,self.passTF.text,self.phoneTF.text,self.accountTF.text];
    [MSNetworkManager postRevertUrl:url params:@{} success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        if (isSuccess) {
            showAlert(@"注册成功,请进行登录");
            [self.navigationController popViewControllerAnimated:YES];
        }
        
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
    } withShowHud:YES];
    
    
}
-(void)textFieldDidChangeSelection:(UITextField *)textField{
    if (textField == self.phoneTF){
        if (textField.text.length > 11) {
            textField.text = [textField.text substringToIndex:11];
        }
    }
    if (textField==self.codeTF){
        if (textField.text.length > 6){
            textField.text = [textField.text substringToIndex:6];
        }
    }
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    
    NSString *shouldText = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (textField == self.accountTF||textField==self.passTF) {
   
        if (shouldText.length>18) {
            shouldText = [shouldText substringToIndex:18];
            return NO;
        }
        
        
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ALPHANUM] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        return [string isEqualToString:filtered];
    }
    
    
    
    return YES;
    
}
- (IBAction)clearAccountTFAction:(UIButton *)sender {
    self.accountTF.text = @"";
}
- (IBAction)loginAction:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

@end
